package com.maimao.kill.job;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.maimao.core.constant.KillConstant;
import com.maimao.core.exception.MaiMaoDaoException;
import com.maimao.core.utils.DateUtils;
import com.maimao.core.utils.StringUtil;
import com.maimao.kill.entity.enums.ActivityEnum;
import com.maimao.kill.service.ScheduleService;
import com.maimao.model.kill.enums.ScheduleCreateType;
import com.maimao.model.kill.input.ScheduleTemplate;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import groovy.util.logging.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 *  定时创建单品秒杀排期
 *
 * @author MaoLin Wang
 * @date 2021/4/8 6:13 下午
 */
@Component
@Slf4j
public class CreateKillScheduleJobHandler {

    @Autowired
    private ScheduleService scheduleService;

    private static final ScheduleTemplate DEFAULT_SCHEDULE_TEMPLATE = new ScheduleTemplate()
            .setActivityId(ActivityEnum.SINGLE_SEC.getId())
            .setCount(KillConstant.DEFAULT_SCHEDULE_COUNT)
            .setCycle(2)
            .setDay(15)
            .setDayEndHour(24)
            .setDayStartHour(8)
            .setStartTime(DateUtils.nextDayBegin().toLocalDate());

    @XxlJob("createKillScheduleJobHandler")
    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public ReturnT createKillScheduleJobHandler() {

        String jobParam = XxlJobHelper.getJobParam();
        ScheduleTemplate template;
        if (!StrUtil.isEmpty(jobParam)) {
            //这里应该进行校验
            template = JSON.parseObject(jobParam, ScheduleTemplate.class);
        } else {
            template = DEFAULT_SCHEDULE_TEMPLATE;
        }
        scheduleService.addByTemplate(template, ScheduleCreateType.JOB.getStatus());

        return ReturnT.SUCCESS;
    }
}
